package handler

import (
	"fmt"

	"database/sql"

	"gitee.com/hp-huiw/family-expense-api/internal/service"
	"gitee.com/hp-huiw/my-go-core/config"
	"github.com/gin-gonic/gin"
)

type AppReleaseLogHandler interface {
	QueryByAppVersion(ctx *gin.Context)
	QueryLatestVersion(ctx *gin.Context)
	ListChangeLog(ctx *gin.Context)
}

func NewAppReleaseLogHandler(db *sql.DB) AppReleaseLogHandler {
	return &appReleaseLogHandler{
		appReleaseLogService: service.NewAppReleaseLogService(db),
	}
}

// Matches /query-by-app-version of http get action.
func (h *appReleaseLogHandler) QueryByAppVersion(ctx *gin.Context) {
	c := ctx.Request.Context()
	appVersion := ctx.Query("appVersion")
	result, err := h.appReleaseLogService.QueryByAppVersion(c, appVersion)

	if err != nil {
		ctx.Error(err)
		return
	}

	SendDataResponse(ctx, result)
}

// Matches /query-latest-version of http get action.
func (h *appReleaseLogHandler) QueryLatestVersion(ctx *gin.Context) {
	c := ctx.Request.Context()
	appVersion := ctx.Query("appVersion")
	result, err := h.appReleaseLogService.QueryLatestVersion(c, appVersion)
	appConfig := config.ConfigLoader.GetAppConfig()

	if err != nil {
		ctx.Error(err)
		return
	}

	SendDataResponse(ctx, map[string]any{
		"hasUpdate":    result != nil,
		"appInfo":      result,
		"sharingH5Url": fmt.Sprintf("%v/%v/app-sharing.html", appConfig.Resource.HttpBaseUrl, appConfig.Resource.H5DirectoryName),
	})
}

// Matches /list-change-log of http get action.
func (h *appReleaseLogHandler) ListChangeLog(ctx *gin.Context) {
	var params struct {
		PageSize  int64 `form:"pageSize"`
		PageIndex int64 `form:"pageIndex"`
	}

	if err := ctx.ShouldBindQuery(&params); err != nil {
		ctx.Error(err)
		return
	}

	c := ctx.Request.Context()

	result, _ := h.appReleaseLogService.ListChangeLog(c, params.PageSize, params.PageIndex)

	SendDataResponse(ctx, result)
}

// Container of AppReleaseLogHandler functions.
type appReleaseLogHandler struct {
	appReleaseLogService service.AppReleaseLogService
}
